# -*- coding: utf-8 -*-
# $ Time    :2022/7/2 9:35
# $ Author  :@柒筱暮
# $ GitHub  :https://github.com/Angie-co
# $ File    :items.py

import settings
import csv
import pymongo


m = 1


class SaveData(object):
    def __init__(self, data: dict):
        self.data = data


class Save2Csv(SaveData):
    def __init__(self, data: dict):
        super().__init__(data)
        self.csv_path = settings.CSV_PATH

    def toCsv(self):
        global m
        with open(self.csv_path, 'a', encoding="utf-8") as f:
            c = csv.DictWriter(f, list(self.data.keys()))
            if m == 1:
                c.writeheader()
            print(self.data)
            c.writerow(self.data)
            m += 1


class Save2Mongo(Save2Csv):
    def __init__(self, data: dict):
        super().__init__(data)
        self.host = settings.MONGO_HOST
        self.port = settings.MONGO_PORT
        self.database = settings.MONGO_DATABASE
        self.collections = settings.MONGO_COLLECTIONS

    def toMongo(self):
        mongo_client = pymongo.MongoClient(host=self.host, port=self.port)
        mongo_client[self.database][self.collections].insert_one(self.data)
